﻿@page "/业务总表当月"
@using System.Diagnostics.CodeAnalysis
@using BootstrapBlazor.OnlyServerZhongShun.Data.dbmodels
@using System.Data
@inject ILogger<Form5> NormalLogger
@inject AuthenticationStateProvider authenticationStateProvider
@inject ToastService ToastService
@inject IConfiguration _congifuration
@inject SqlSugarScope _SqlSugarScope
@attribute [Authorize(Roles = "超级管理员,业务总, 业务经理, 业务员")]
<style>
    .multi-select {
        --bb-multi-select-min-height: 26px;
    }

    .table thead th,   .table tbody td  {
        border: 1px solid  #000 !important;
    }
</style>

<div class="row g-1">
    <div class="col-5">
        <BootstrapInputGroup>
            <BootstrapInputGroupLabel DisplayText="查询日期" />
            <DateTimeRange @bind-Value="@NormalDateTimeRangeValue" OnConfirm="OnNormalConfirm" ShowSidebar="true" ViewMode="DatePickerViewMode.Date" IsEditable="true" DateFormat="yyyy-MM-dd">
                <TimePickerSetting ShowClockScale="true" IsAutoSwitch="false" />
            </DateTimeRange>
        </BootstrapInputGroup>
    </div>
    @* <div class="col-4 col-sm-4">
        <BootstrapInputGroup>
            <BootstrapInputGroupLabel DisplayText="客户" />
            <Select IsVirtualize="true" Items="客户列表Items" @bind-Value="选中客户" OnSearchTextChanged="OnSearchTextChanged" ShowSearch="true" IsClearable="true"></Select>
        </BootstrapInputGroup>
    </div> *@
    <div class="col-3">
        <BootstrapInputGroup>
            <BootstrapInputGroupLabel DisplayText="部门" />
            <MultiSelect Items="@部门Items" @bind-Value="@选中部门List" OnSelectedItemsChanged="@部门选择改变事件" ShowToolbar="true" />
        </BootstrapInputGroup>
    </div>

    <div class="col-3">
        <BootstrapInputGroup>
            <BootstrapInputGroupLabel DisplayText="养殖类别" />
            <Select IsVirtualize="true" Items="养殖类别Items" @bind-Value="选中养殖类别" ShowSearch="false" IsClearable="true"></Select>
        </BootstrapInputGroup>
    </div>

    <div class=" col-md-1">
        <Button OnClick="@Button_chaxun_Click" IsAsync="true" Color="Color.Primary">查询</Button>
        <Button OnClick="@Button_daochu" Color="Color.Info">导出</Button>
        </div>
    
</div>
<Table Class="table-bordered-bold" TItem="DynamicObject" DynamicContext="DataTableDynamicContext"
       IsBordered="true" IsMultipleSelect="false" ShowToolbar="true"  ShowRefresh="false" ShowDefaultButtons="false" IsPagination="true"
       OnSort="OnSort" ShowFooter="false" PageItemsSource="new int[]{1000,2000,3000,4000,5000,10000}" IsStriped="false" SetRowClassFormatter="@SetRowClassFormatter"
       Height="500" IsFixedHeader="true" TableSize="TableSize.Compact">
</Table>

@code {
    private string username;

    [Inject]
    [NotNull]
    private ITableExport? TableExport { get; set; }
    [Inject]
    [NotNull]
    private ToastService? Toast { get; set; }

    private List<View_Custom> View_CustomList = new List<View_Custom>();
    private List<View_Depart> View_DepartList = new List<View_Depart>();
    //时间范围
    private DateTimeRangeValue NormalDateTimeRangeValue { get; set; } = new();

    private IEnumerable<SelectedItem> 客户列表Items => View_CustomList.Select(i => new SelectedItem(i.cCusCode!, i.cCusName!)).ToList();
    private IEnumerable<SelectedItem> 部门Items => View_DepartList.Select(i => new SelectedItem(i.cDepCode!, i.cDepName!)).ToList();
    [NotNull]
    private IEnumerable<SelectedItem>? 查询类别 { get; set; } = new List<SelectedItem>(new List<SelectedItem>
    {
        new SelectedItem { Text = "产品", Value = "产品" },
        new SelectedItem { Text = "类别", Value = "类别"}
    });


    private List<View_Custom> view_Customs = new List<View_Custom>();
    private SelectedItem? 选中养殖类别 { get; set; }
    private IEnumerable<SelectedItem> 养殖类别Items => view_Customs.Select(i => new SelectedItem(i.养殖类别!, i.养殖类别!)).ToList();

    private static string? SetRowClassFormatter(DynamicObject item) => (bool)item.GetType().GetProperty("部门")?.GetValue(item).ToString().Contains("计") ? "table-success" : null;

    private SelectedItem? 选中客户 { get; set; }
    private IEnumerable<string> 选中部门List { get; set; }
    private string 选中部门InStr = "";
    private string 选中查询类别 { get; set; }
    //表格数据
    [NotNull]
    private DataTableDynamicContext? DataTableDynamicContext { get; set; }
    private DataTableDynamicContext? DataTableDynamicContextDetail { get; set; }



    protected override async void OnInitialized()
    {
        var authState = await authenticationStateProvider.GetAuthenticationStateAsync();
        var user = authState.User;
        username = user.Identity.Name;
        //今年1月1日
        NormalDateTimeRangeValue.Start = new DateTime(DateTime.Now.Year, 1, 1);
        //今天
        NormalDateTimeRangeValue.End = DateTime.Now.AddDays(-1);

        View_CustomList = _SqlSugarScope.Queryable<View_Custom>().ToList();
        //加一个请选择
        View_CustomList.Insert(0, new View_Custom { cCusCode = "", cCusName = "请选择" });

        //读取配置文件
        UserDataAuth userDataAuth = _SqlSugarScope.Queryable<UserDataAuth>().Where(it => it.UserName == username).First();
        List<Guid> guids = userDataAuth.CanViewDepart.Split(",").ToList().Select(it => Guid.Parse(it)).ToList();
        List<Sys_Department> depts = _SqlSugarScope.Queryable<Sys_Department>().Where(it => guids.Contains(it.DepartmentId)).ToList();
        List<string> deptNames = depts.Select(it => it.DepartmentName).ToList();
        var PaiChuBuMen = _congifuration.GetSection("PaiChuBuMen").Value;
        List<View_Depart> deptss = _SqlSugarScope.Queryable<View_Depart>().Where($"cDepCode not in ({PaiChuBuMen})").ToList();
        View_DepartList = deptss.Where(it => deptNames.Contains(it.cDepName)).ToList();
        // //加一个请选择
        // View_DepartList.Insert(0, new View_Depart { cDepCode = "", cDepName = "请选择" });
        List<View_Custom> cus = _SqlSugarScope.Queryable<View_Custom>().Where(it => !string.IsNullOrEmpty(it.养殖类别)).Distinct().Select(it => new View_Custom { 养殖类别 = it.养殖类别 }).ToList();
        view_Customs = cus;
        view_Customs.Insert(0, new View_Custom { 养殖类别 = "请选择" });
        view_Customs.Add(new View_Custom { 养殖类别 = "非小棚虾" });
    }


    private Task OnNormalConfirm(DateTimeRangeValue value)
    {
        NormalLogger.LogDebug($"选择的时间范围是: {value.Start:yyyy-MM-dd HH:mm:ss} - {value.End:yyyy-MM-dd HH:mm:ss}");
        //遍历输出选中的客户
        if (选中客户 != null)
        {
            NormalLogger.LogDebug($"选中的客户是: {选中客户.Text}");
        }
        //遍历输出选中的部门
        if (选中部门List != null)
        {
            foreach (var item in 选中部门List)
            {

            }
        }
        return Task.CompletedTask;
    }
    private IEnumerable<SelectedItem> OnSearchTextChanged(string searchText)
    {
        return View_CustomList.Where(i => i.cCusName!.Contains(searchText, StringComparison.OrdinalIgnoreCase)).Select(i => new SelectedItem(i.cCusCode!, i.cCusName!));
    }

    private Task 部门选择改变事件(IEnumerable<SelectedItem> items)
    {
        选中部门InStr = string.Join("','", items.Select(it => it.Text).ToArray());
        return Task.CompletedTask;
    }

    private async Task<bool> OnExportAsync(ITableExportDataContext<DynamicObject> context)
    {
        // 导出符合条件的所有数据 data
        var ret = await TableExport.ExportExcelAsync(DataTableDynamicContext.GetItems(), context.Columns, $"原06代理业务数据穿透分析_{DateTime.Now:yyyyMMddHHmmss}.xlsx");

        // 返回 true 时自动弹出提示框
        // await ShowToast(ret);
        return ret;
    }
    private async void Button_daochu(MouseEventArgs e)
    {
        // 导出符合条件的所有数据 data
        if (DataTableDynamicContext != null)
        {
            //复制一个table用来导出
            DataTable dt = DataTableDynamicContext.DataTable.Copy();
            //增加一行合计
            DataRow dr = dt.NewRow();
            // dr["部门"] = "合计";
            dr["本年销售额"] = dt.Compute("sum(本年销售额)", "");
            dr["往年销售额"] = dt.Compute("sum(往年销售额)", "");
            dr["本月销售额"] = dt.Compute("sum(本月销售额)", "");
            dr["同期销售额"] = dt.Compute("sum(同期销售额)", "");

            dr["本月差异"] = Convert.ToDecimal(dr["本月销售额"]) - Convert.ToDecimal(dr["同期销售额"]);
            dr["累计差异率"] = ((decimal)dt.Compute("sum(本年销售额)", "") - (decimal)dt.Compute("sum(往年销售额)", "")) / (decimal)dt.Compute("sum(往年销售额)", "");
            dr["本月差异率"] = ((decimal)dt.Compute("sum(本月销售额)", "") - (decimal)dt.Compute("sum(同期销售额)", "")) / (decimal)dt.Compute("sum(同期销售额)", "");


            dt.Rows.Add(dr);
            DataTableDynamicContext dataTable = new DataTableDynamicContext(dt);
            var ret = await TableExport.ExportExcelAsync(dataTable.GetItems(), DataTableDynamicContext.GetColumns(), $"业务发货总表_{DateTime.Now:yyyyMMddHHmmss}.xlsx");

            // var ret = await TableExport.ExportExcelAsync(DataTableDynamicContext.GetItems(), DataTableDynamicContext.GetColumns(), $"原06代理业务数据穿透分析_{DateTime.Now:yyyyMMddHHmmss}.xlsx");
            ToastService.Success("提示", "导出成功");
        }

    }
    private string OnSort(string sortName, SortOrder sortOrder)
    {

        string sortString = "";
        if (sortOrder == SortOrder.Asc)
        {
            sortString = $"{sortName} asc";
        }
        else if (sortOrder == SortOrder.Desc)
        {
            sortString = $"{sortName} desc";
        }
        else
        {
            sortString = $"{sortName}";
        }
        DataTable sortTable = DataTableDynamicContext.DataTable.Clone();

        DataView dv = DataTableDynamicContext.DataTable.DefaultView;
        dv.Sort = sortString;
        sortTable = dv.ToTable();

        DataTableDynamicContext = new DataTableDynamicContext(sortTable, (context, col) =>

            {
                //所有列可排序
                col.Sortable = true;
                col.DefaultSort = true;
            });
        StateHasChanged();
        return sortString;
    }

    private async Task<bool> OnExportDetailAsync(ITableExportDataContext<DynamicObject> context)
    {
        // 导出符合条件的所有数据 data
        var ret = await TableExport.ExportExcelAsync(DataTableDynamicContextDetail.GetItems(), context.Columns, $"原06代理业务数据穿透分析明细_{DateTime.Now:yyyyMMddHHmmss}.xlsx");

        // 返回 true 时自动弹出提示框
        // await ShowToast(ret);
        return ret;
    }

    private string OnSortDetail(string sortName, SortOrder sortOrder)
    {

        string sortString = "";
        if (sortOrder == SortOrder.Asc)
        {
            sortString = $"{sortName} asc";
        }
        else if (sortOrder == SortOrder.Desc)
        {
            sortString = $"{sortName} desc";
        }
        else
        {
            sortString = $"{sortName}";
        }
        DataTable sortTable = DataTableDynamicContextDetail.DataTable.Clone();

        DataView dv = DataTableDynamicContextDetail.DataTable.DefaultView;
        dv.Sort = sortString;
        sortTable = dv.ToTable();

        DataTableDynamicContextDetail = new DataTableDynamicContext(sortTable, (context, col) =>

            {
                //所有列可排序
                col.Sortable = true;
                col.DefaultSort = true;
            });
        StateHasChanged();
        return sortString;
    }

    private decimal sum1;
    private decimal sum2;
    private decimal sum3;
    private decimal sum4;
    private decimal sum5;
    private decimal sum6;
    private decimal sum7;
    private decimal sum8;

    private async void Button_chaxun_Click(MouseEventArgs e)
    {
        //客户发货排名
        string sql;
        string 年度 = this.NormalDateTimeRangeValue.End.Year.ToString();
        string 今年开始日期 = this.NormalDateTimeRangeValue.Start.ToString("yyyy-MM-dd");
        string 今年结束日期 = this.NormalDateTimeRangeValue.End.ToString("yyyy-MM-dd");
        string 去年开始日期 = this.NormalDateTimeRangeValue.Start.AddYears(-1).ToString("yyyy-MM-dd");
        string 去年结束日期 = this.NormalDateTimeRangeValue.End.AddYears(-1).ToString("yyyy-MM-dd");
        string 去年 = 去年开始日期.Substring(0, 4);
        string 今年sql;
        string 去年sql;
        string 今年本月开始 = this.NormalDateTimeRangeValue.End.ToString("yyyy-MM-01");
        string 去年本月开始 = this.NormalDateTimeRangeValue.End.AddYears(-1).ToString("yyyy-MM-01");
        // string loginuser = username;
        string loginuser = "admin";
        sql = "SELECT DepartmentName FROM [netcoredev].[dbo].[View_PersonDepart] where  cPersonName='" + loginuser + "'";
        string depart = _SqlSugarScope.Ado.GetString(sql);
        string guid = Guid.NewGuid().ToString();  ///本次查询统一的
        if (string.IsNullOrEmpty(选中部门InStr) == true)
        {
            选中部门InStr += string.Join("','", View_DepartList.Select(it => it.cDepName));
        }
        string 部门清单 = "('" + 选中部门InStr + "')";

        sql = "select docyear, dbname FROM      Tset where docyear='" + 年度 + "'";
        DataTable tb1 = _SqlSugarScope.Ado.GetDataTable(sql);
        if (tb1.Rows.Count > 0)
        {
            今年sql = tb1.Rows[0]["dbname"].ToString();
            sql = "delete T客户发货 where usercode='" + loginuser + "'";
            _SqlSugarScope.Ado.ExecuteCommand(sql);
            //处理今年(今年sql)
            //1,塞入空客户
            #region
            sql = "insert into  T客户发货 (guid, usercode, Depart, cCusCode, cDLCode,irowno, cPersonCode, dDate ,";
            sql += " 本期销售额, 同期销售额)";
            sql += "select '" + guid + "','" + loginuser + "','" + depart + "', cCusCode ,cDLCode,irowno,cPersonCode,dDate,";
            sql += " iMoney,0 from View_发票明细 where 1=1 ";
            if (loginuser != "admin")
            {
                sql += " and cCusCode in (SELECT  cCusCode FROM View_CustomDepart where  cDepName='" + depart + "')";
                sql += " and cCusCode in (SELECT  cCusCode FROM TPersonCustom where cPersonName='" + loginuser + "')";
            }
            sql += " and period='" + 年度 + "' and dDate<='" + 今年结束日期 + "'and dDate>='" + 今年开始日期 + "'";

            _SqlSugarScope.Ado.ExecuteCommand(sql);

            sql = "insert into  T客户发货 (guid, usercode, Depart, cCusCode, cDLCode,irowno, cPersonCode, dDate ,";
            sql += " 本期销售额, 同期销售额)";
            sql += "select '" + guid + "','" + loginuser + "','" + depart + "', cCusCode ,cDLCode,irowno,cPersonCode,dDate,";
            sql += " 0,iMoney from View_发票明细 where 1=1 ";
            if (loginuser != "admin")
            {
                sql += " and cCusCode in (SELECT  cCusCode FROM View_CustomDepart where  cDepName='" + depart + "')";
                sql += " and cCusCode in (SELECT  cCusCode FROM TPersonCustom where cPersonName='" + loginuser + "')";
            }
            sql += " and period='" + 去年 + "' and dDate<='" + 去年结束日期 + "'and dDate>='" + 去年开始日期 + "'";

            _SqlSugarScope.Ado.ExecuteCommand(sql);
            #endregion
            //开始更新本期销售额

            //2塞入空客户
            #region
            sql = "delete T客户回款 where usercode='" + loginuser + "'";
            _SqlSugarScope.Ado.ExecuteCommand(sql);
            sql = "insert into  T客户回款 (guid, usercode,  Depart, cCusCode, iid, id, cPersonCode,dDate,  本期回款额, 同期回款额)";
            sql += "select '" + guid + "','" + loginuser + "','" + depart + "', cCusCode ,cDLCode,irowno,cPersonCode,dDate,";
            sql += " iMoney,0 from View_发票明细 where 1=1 ";
            if (loginuser != "admin")
            {
                sql += " and cCusCode in (SELECT  cCusCode FROM View_CustomDepart where  cDepName='" + depart + "')";
                sql += " and cCusCode in (SELECT  cCusCode FROM TPersonCustom where cPersonName='" + loginuser + "')";
            }
            sql += " and period='" + 年度 + "' and dDate<='" + 今年结束日期 + "'and dDate>='" + 今年本月开始 + "'";

            _SqlSugarScope.Ado.ExecuteCommand(sql);

            sql = "insert into  T客户回款 (guid, usercode,  Depart, cCusCode, iid, id, cPersonCode,dDate,  本期回款额, 同期回款额)";
            sql += "select '" + guid + "','" + loginuser + "','" + depart + "', cCusCode ,cDLCode,irowno,cPersonCode,dDate,";
            sql += " 0,iMoney from View_发票明细 where 1=1 ";
            if (loginuser != "admin")
            {
                sql += " and cCusCode in (SELECT  cCusCode FROM View_CustomDepart where  cDepName='" + depart + "')";
                sql += " and cCusCode in (SELECT  cCusCode FROM TPersonCustom where cPersonName='" + loginuser + "')";
            }
            sql += " and period='" + 去年 + "' and dDate<='" + 去年结束日期 + "'and dDate>='" + 去年本月开始 + "'";

            _SqlSugarScope.Ado.ExecuteCommand(sql);
            #endregion
            //更新客户
            //sql = "update  a set a.代理商名称=b.cCusName ";
            //sql += " from T客户发货 a, View_Custom b where a.cCusCode=b.cCusCode and a.guid='" + guid + "'";
            //_SqlSugarScope.Ado.ExecuteCommand(sql);
            ////更新销售员
            //sql = "update  a set a.销售员=b.cPersonName ";
            //sql += " from T客户发货 a, View_Person b where a.cPersonCode=b.cPersonCode and a.guid='" + guid + "'";
            //_SqlSugarScope.Ado.ExecuteCommand(sql);
            //更新部门
            sql = "update  a set a.部门=b.DepartmentName,a.Depart=b.[cDepCode] ";
            sql += " from T客户发货 a, View_PersonDepart b where a.cPersonCode=b.cPersonCode and a.guid='" + guid + "'";
            _SqlSugarScope.Ado.ExecuteCommand(sql);
            //更新事业部（就是一级部门）
            sql = "update  a set a.事业部=b.事业部 ";
            sql += " from T客户发货 a, T事业部 b where  substring(a.[Depart] ,0,4)=b.编号 and a.guid='" + guid + "'";
            _SqlSugarScope.Ado.ExecuteCommand(sql);

            ////更新客户
            //sql = "update  a set a.代理商名称=b.cCusName ";
            //sql += " from T客户回款 a, View_Custom b where a.cCusCode=b.cCusCode and a.guid='" + guid + "'";
            //_SqlSugarScope.Ado.ExecuteCommand(sql);
            //更新销售员
            //sql = "update  a set a.销售员=b.cPersonName ";
            //sql += " from T客户回款 a, View_Person b where a.cPersonCode=b.cPersonCode and a.guid='" + guid + "'";
            //_SqlSugarScope.Ado.ExecuteCommand(sql);
            //更新部门
            sql = "update  a set a.部门=b.DepartmentName,a.Depart=b.[cDepCode] ";
            sql += " from T客户回款 a, View_PersonDepart b where a.cPersonCode=b.cPersonCode and a.guid='" + guid + "'";
            _SqlSugarScope.Ado.ExecuteCommand(sql);
            //更新事业部（就是一级部门）
            sql = "update  a set a.事业部=b.事业部 ";
            sql += " from T客户回款 a, T事业部 b where  substring(a.[Depart] ,0,4)=b.编号 and a.guid='" + guid + "'";
            _SqlSugarScope.Ado.ExecuteCommand(sql);

            //养殖类别
            sql = "update  a set a.养殖类别=b.养殖类别 ";
            sql += " from T客户发货 a, View_Custom b where  a.cCusCode=b.cCusCode and a.guid='" + guid + "'";
            _SqlSugarScope.Ado.ExecuteCommand(sql);
            //养殖类别
            sql = "update  a set a.养殖类别=b.养殖类别 ";
            sql += " from T客户回款 a, View_Custom b where  a.cCusCode=b.cCusCode and a.guid='" + guid + "'";
            _SqlSugarScope.Ado.ExecuteCommand(sql);

            //显示数据
            sql = @"select t.部门,t.[Depart],t.事业部,Convert(decimal(18,1),sum(本期销售)/10000) 今年业绩, Convert(decimal(18,1),sum(同期销售)/10000) 往年业绩 ,Convert(decimal(18,1),(sum(本期销售)-sum(同期销售))/10000) 业绩差异,
            Convert(decimal(18,1),sum(本期回款)/10000) 本月金额,Convert(decimal(18,1),sum(同期回款)/10000) 上年本月金额,Convert(decimal(18,1),(sum(本期回款)-sum(同期回款) )/10000) 本月差异,0.0  累计差异率,0.0 本月差异率
            from (SELECT 事业部,substring([Depart] ,0,4) Depart,部门,sum(本期销售额) 本期销售, sum(同期销售额) 同期销售 ,0 本期回款 ,0 同期回款
            FROM T客户发货 where guid='" + guid + "' ";
            // Session["代理商名称"] = this.TextBox客户.Text.Trim().Replace("-", "");
            if (string.IsNullOrEmpty(this.选中客户?.Text) == false && this.选中客户?.Text != "请选择")
            {
                sql += " and 代理商名称 like '%" + this.选中客户.Text + "%'";
            }
            if (this.选中养殖类别?.Text != "请选择" && this.选中养殖类别?.Text != "非小棚虾")
            {
                sql += " and 养殖类别='" + this.选中养殖类别.Text + "'";
            }
            if (this.选中养殖类别?.Text != "请选择" && this.选中养殖类别?.Text == "非小棚虾")
            {
                sql += " and 养殖类别 is null";
            }
            sql += " and 部门 in " + 部门清单;
            sql += " group by 事业部,substring([Depart] ,0,4) ,部门";
            sql += @" union all
                SELECT 事业部,substring([Depart] ,0,4) Depart,部门, 0 本期销售, 0 同期销售 ,sum([本期回款额]) 本期回款 ,sum([同期回款额]) 同期回款
                FROM [T客户回款] where guid='" + guid + "'";
            if (string.IsNullOrEmpty(this.选中客户?.Text) == false && this.选中客户?.Text != "请选择")
            {
                sql += " and 代理商名称 like '%" + this.选中客户.Text + "%'";
            }
            if (this.选中养殖类别?.Text != "请选择" && this.选中养殖类别?.Text != "非小棚虾")
            {
                sql += " and 养殖类别='" + this.选中养殖类别.Text + "'";
            }
            if (this.选中养殖类别?.Text != "请选择" && this.选中养殖类别?.Text == "非小棚虾")
            {
                sql += " and 养殖类别 is null";
            }
            sql += " and 部门 in " + 部门清单;
            sql += " group by 事业部,substring([Depart] ,0,4),部门)  t group by 事业部,t.[Depart],部门 order by t.[Depart]";
            DataTable dataTableHZ = _SqlSugarScope.Ado.GetDataTable(sql);
            sql = " delete T客户发货 where  guid='" + guid + "' ";
            sql += " delete T客户回款 where  guid='" + guid + "' ";
            _SqlSugarScope.Ado.ExecuteCommand(sql);

            if (dataTableHZ != null)
            {

                for (int i = 0; i < dataTableHZ.Rows.Count; i++)
                {
                    DataRow dr = dataTableHZ.Rows[i];

                    decimal 累计差异率 = 0;
                    decimal 本月差异率 = 0;
                    if (decimal.TryParse(dr["往年业绩"].ToString(), out decimal result) == true && result != 0)
                    {
                        decimal.TryParse(dr["往年业绩"].ToString(), out decimal a);
                        decimal.TryParse(dr["今年业绩"].ToString(), out decimal b);
                        累计差异率 = ((b-a) / a);
                        dataTableHZ.Rows[i]["累计差异率"] = 累计差异率;

                    }

                    if (decimal.TryParse(dr["上年本月金额"].ToString(), out decimal result2) == true && result2 != 0)
                    {
                        // decimal a = Pub.ToDecimal(dr["同期回款额"].ToString());
                        // decimal b = Pub.ToDecimal(dr["同期销售额"].ToString());

                        decimal.TryParse(dr["上年本月金额"].ToString(), out decimal a);
                        decimal.TryParse(dr["本月金额"].ToString(), out decimal b);
                        本月差异率 = ((b-a) / a);
                        dataTableHZ.Rows[i]["本月差异率"] = 本月差异率; ;
                    }

                }
            }

            DataTable resultTable = dataTableHZ.Clone();
            //根据事业部计算一行合计值，并插入到对应事业部后面
            if (dataTableHZ != null && dataTableHZ.Rows.Count > 0)
            {
                //添加总计行
                DataRow drTotal = dataTableHZ.NewRow();
                drTotal["部门"] = "总计";
                drTotal["事业部"] = "";
                drTotal["今年业绩"] = dataTableHZ.Compute("sum(今年业绩)", "");
                drTotal["往年业绩"] = dataTableHZ.Compute("sum(往年业绩)", "");
                drTotal["本月金额"] = dataTableHZ.Compute("sum(本月金额)", "");
                drTotal["上年本月金额"] = dataTableHZ.Compute("sum(上年本月金额)", "");
                drTotal["业绩差异"] = Convert.ToDecimal(drTotal["今年业绩"]) - Convert.ToDecimal(drTotal["往年业绩"]);
                drTotal["本月差异"] = Convert.ToDecimal(drTotal["本月金额"]) - Convert.ToDecimal(drTotal["上年本月金额"]);
                if ((decimal)dataTableHZ.Compute("sum(往年业绩)", "") != 0)
                {
                    drTotal["累计差异率"] = ((decimal)dataTableHZ.Compute("sum(今年业绩)", "") - (decimal)dataTableHZ.Compute("sum(往年业绩)", "")) / (decimal)dataTableHZ.Compute("sum(往年业绩)", "");
                }      
                if ((decimal)dataTableHZ.Compute("sum(上年本月金额)", "") != 0)
                {
                    drTotal["本月差异率"] = ((decimal)dataTableHZ.Compute("sum(本月金额)", "") - (decimal)dataTableHZ.Compute("sum(上年本月金额)", "")) / (decimal)dataTableHZ.Compute("sum(上年本月金额)", "");
                }


                //取所有的事业部
                var 事业部 = dataTableHZ.AsEnumerable().Select(dr => dr.Field<string>("事业部")).Distinct().ToList();
                foreach (var item in 事业部)
                {
                    //再根据 部门排序
                    // 获取当前事业部的所有行
                    var rows = dataTableHZ.AsEnumerable()
                                          .Where(row => row.Field<string>("事业部") == item);

                    // 将当前事业部的行添加到结果表
                    foreach (var row in rows)
                    {
                        resultTable.ImportRow(row);
                    }
                    if (rows.Count() > 1)
                    {
                        // 计算合计行
                        DataRow dr = resultTable.NewRow();
                        dr["部门"] = item + "合计";
                        dr["事业部"] = item + "合计";
                        dr["今年业绩"] = dataTableHZ.Compute("sum(今年业绩)", "事业部='" + item + "'");
                        dr["往年业绩"] = dataTableHZ.Compute("sum(往年业绩)", "事业部='" + item + "'");
                        dr["本月金额"] = dataTableHZ.Compute("sum(本月金额)", "事业部='" + item + "'");
                        dr["上年本月金额"] = dataTableHZ.Compute("sum(上年本月金额)", "事业部='" + item + "'");
                        dr["业绩差异"] = Convert.ToDecimal(dr["今年业绩"]) - Convert.ToDecimal(dr["往年业绩"]);
                        dr["本月差异"] = Convert.ToDecimal(dr["本月金额"]) - Convert.ToDecimal(dr["上年本月金额"]);
                        if (Convert.ToDecimal(dr["往年业绩"]) != 0)
                        {
                            dr["累计差异率"] = Convert.ToDecimal(dr["业绩差异"]) / Convert.ToDecimal(dr["往年业绩"]);
                        }
                        if (Convert.ToDecimal(dr["上年本月金额"]) != 0)
                        {
                            dr["本月差异率"] = Convert.ToDecimal(dr["本月差异"]) / Convert.ToDecimal(dr["上年本月金额"]);
                        }
                        
                        


                    // 将合计行添加到结果表
                        resultTable.Rows.Add(dr);
                    }
                }
                //添加总计行
                DataRow drTotalNew = resultTable.NewRow();
                drTotalNew.ItemArray = drTotal.ItemArray.Clone() as object[];
                
                // Set the values for drTotal here
                resultTable.Rows.Add(drTotalNew);
            }

            //resultTable移除 depart、事业部 列
            resultTable.Columns.Remove("Depart");
            resultTable.Columns.Remove("事业部");
            //修改列名
            resultTable.Columns["部门"].ColumnName = "部门";
            resultTable.Columns["今年业绩"].ColumnName = "本年销售额";
            resultTable.Columns["往年业绩"].ColumnName = "往年销售额";
            resultTable.Columns["本月金额"].ColumnName = "本月销售额";
            resultTable.Columns["上年本月金额"].ColumnName = "同期销售额";
            resultTable.Columns["业绩差异"].ColumnName = "累计差异";
            resultTable.Columns["本月差异"].ColumnName = "本月差异";

            DataTableDynamicContext = new DataTableDynamicContext(resultTable, (context, col) =>
           {
               //所有列可排序
               // col.Sortable = true;
               // col.DefaultSort = true;
               var propertyName = col.GetFieldName();
               if (col.GetFieldName() == "累计差异率" || col.GetFieldName() == "本月差异率")
               {
                   col.FormatString = "P1";
               }
               //如果是部门列，则按钮形式显示
               // if (propertyName == "事业部")
               // {
               //     //新建Template
               //     col.Template = (item) =>
               //      {
               //          return new RenderFragment(builder =>
               //      {
               //          //通过反射获取当前列的值
               //           var value = item.GetType().GetProperty(propertyName)?.GetValue(item);
               //           builder.OpenComponent(0, typeof(Button));
               //           builder.AddAttribute(1, "Color", Color.Primary);
               //          // builder.AddAttribute(2, "Size", ButtonSize.Small);
               //           builder.AddAttribute(3, "ChildContent", (RenderFragment)(builder =>
               //           {
               //               builder.AddContent(0, value);
               //           }));

               //          //加点击事件

               //           builder.AddAttribute(0, nameof(Button.OnClick), EventCallback.Factory.Create<MouseEventArgs>(this, (e) =>
               //           {
               //               //获取按钮text
               //               var text = value.ToString();
               //               string 事业部 = text;
               //               // chaxun(事业部);
               //           }));


               //          // builder.AddAttribute(4, nameof(Button.OnClick), OnClick);

               //           builder.CloseComponent();
               //       });
               //      };
               //     //设置单元格渲染事件
               //     col.OnCellRender = OnCellRenderHandler;

               // }
           });
            await ToastService.Information("提示", "查询成功");
        }
        else
        {
            await ToastService.Success("提示", "选择的日期有误", autoHide: true);
        }
    }

    private static void OnCellRenderHandler(TableCellArgs args)
    {
        //获取行数据
        var row = args.Row;
        //获取事业部列的值
        var value = row.GetType().GetProperty("事业部")?.GetValue(row);
        //如果列的值包含 "合计"则设置背景色
        if (value.ToString().Contains("合计"))
        {
           
        }
    }


}
